/**
 * 使用
 * import axios from "../common/axios.js"
 *
 * 跳过异常处理
 * axios.post/get('/api', null, {skipErrorHandler: true})
 */
import './plugins/axios/1.4.0.min.js'
import env from "../common/env.js"
import storageUtil from "./util/storageUtil.js"

axios.defaults.baseURL = env.axiosBaseUrl()
// 请求超时
axios.defaults.timeout = 2000

/**
 * 省缺的显示错误消息的方法, 应按需重写本方法!
 * @param msg 用户可见的错误消息
 */
axios.handlerErrMsg = msg => {
  console.error(msg)
}
/**
 * 省缺的请求成功处理器
 */
axios.handleSuccess = response => {
  // console.log('success', response)
  return response
}

axios.interceptors.request.use(config => {
  config.headers['tk'] = storageUtil.getString('tk', '')

  if (config.method === 'get') {
    if (config.url.indexOf('?') === -1) {
      config.url = config.url + '?_=' + (new Date().getTime())
    } else {
      config.url = config.url + '&_=' + (new Date().getTime())
    }
  }
  return config
})

//处理请求异常
axios.interceptors.response.use(response => {
  return axios.handleSuccess(response)
}, err => {
  if (err.config.skipErrorHandler) return Promise.reject() //自定义参数,跳过异常处理
  // console.log('err', err)
  if (err.response) {
    //http请求异常
    let data = err.response.data
    if (!data) {
      console.error("对象格式异常??", err, new Error())
      return Promise.reject()
    }
    if (!data.status) {
      //未知
      console.error("未知异常", err.response.status, err.message, new Error())
      axios.handlerErrMsg('系统错误')
    } else if (data.status === 400) {
      //给用户看的异常消息
      axios.handlerErrMsg(data.message)
    } else if (data.status === 401) {
      window.location.href = './login.html'
    } else {
      //其他网络异常 404, 500, 403
      console.log(data.status, data.message, new Error())
      axios.handlerErrMsg('系统错误')
    }
    return Promise.reject()
  } else if (err.request) {
    //axios.Network Error, 超时...
    console.log("网络异常", err.message, new Error())
    axios.handlerErrMsg('网络异常')
    return Promise.reject()
  }
  // console.log('err.ed')
  return Promise.reject(err)
})

export default axios